package cn.tansanqinger.service.verification.impl;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;

import cn.tansanqinger.dao.nosql.IVerificationCode;
import cn.tansanqinger.service.verification.IVerificationService;
import cn.tansanqinger.util.VerificationUtil;

@Controller
public class VerificationImpl implements IVerificationService{
	
	@Autowired
	private IVerificationCode iVerficationCode;
    @Autowired
    JavaMailSenderImpl mailSender;//邮件发送
    
	@Override
	public byte[] messageInit(String key) {
		byte[] bytes = null ;
		try {
			File file = ResourceUtils.getFile("classpath:static/verification.jpg");
			FileInputStream inputStream = new FileInputStream(file);
			VerificationUtil vc = new VerificationUtil();
			BufferedImage bi = vc.getImage();
			VerificationUtil.output(bi, new FileOutputStream(file));//调用静态方法将文件保存到指定位置
			int length = inputStream.available();
			bytes = new byte[length];
	        inputStream.read(bytes, 0, length);
	        iVerficationCode.saveEmailMessageNoSQL(key, vc.getText());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bytes;
	}
	@Async
	@Override
	public void emailVerification(String email) {
		if(email!=null) {
			String uuid = UUID.randomUUID().toString().substring(0, 8);
	        SimpleMailMessage mailMessage = new SimpleMailMessage();
	        mailMessage.setSubject("邮箱验证");
	        mailMessage.setText("尊敬的"+email+"用户！\n"+"感谢您对我们网址的认可！\n您的验证码为 "+uuid+" ，\n请您尽快填写，验证码请勿泄露给他人，有效时间5分钟。\n【碳氢科技】");
	        mailMessage.setTo(email);
	        mailMessage.setFrom("message@tansanqinger.cn");
	        mailSender.send(mailMessage);
	        iVerficationCode.saveEmailMessageNoSQL(email, uuid);
		}
	}
}
